package org.fxd.send;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SendUtil {
	public static final String IP = "127.0.0.1";
	public static final int PORT = 15233;

	public static final String URL = "http://" + IP + ":" + PORT + "/zweixin-turn/push";

	/**
	 * 
	 * @param system    所属系统: 审批系统为 OA
	 * @param telephone
	 * @param first
	 * @param keyword1
	 * @param keyword2
	 * @param keyword3
	 * @param keyword4
	 * @param keyword5
	 * @param remark
	 */
	public static void sendMsg(String system, String telephone, String first, String keyword1, String keyword2,
			String keyword3, String keyword4, String keyword5, String remark) {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("system", system);
			map.put("telephone", telephone);
			map.put("first", first);
			map.put("keyword1", keyword1);
			map.put("keyword2", keyword2);
			map.put("keyword3", keyword3);
			map.put("keyword4", keyword4);
			map.put("keyword5", keyword5);
			map.put("remark", remark);

			URL url = new URL(URL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			connection.setDoInput(true); // 设置可输入
			connection.setDoOutput(true); // 设置该连接是可以输出的
			connection.setRequestMethod("POST"); // 设置请求方式
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

			String params = turnMap2Params(map);

			PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
			pw.write(params);
			pw.flush();
			pw.close();

			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			String line = null;
			StringBuilder result = new StringBuilder();
			while ((line = br.readLine()) != null) { // 读取数据
				result.append(line + "\n");
			}
			connection.disconnect();

			System.err.println(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String turnMap2Params(Map<String, Object> map) {
		final String line = "@key=@val&";
		String params = "";
		Set<String> keys = map.keySet();
		for (String key : keys) {
			params += line.replace("@key", key).replace("@val", map.get(key) + "");
		}
		return params;
	}

	public static void main(String[] args) {
		SendUtil.sendMsg("OA", "18649325921", "审批提示", "OA系统", "审批流程", "新的请假", "张三", "申请人提交", "请您尽快审批");
	}

}
